package com.example.xinwen;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import adapter.NewsAdapter;
import bean.NewsBean;
import dbhelper.NewsDBUtils;
import utils.NewsUtils;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    private static String result = "�������Json�����ľW�URL";
    private Context mContext;
    private TextView textView;
    NewsUtils newsUtils;
    List<NewsBean> listNewsBean;
    ListView listview;
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            listNewsBean = (List<NewsBean>) msg.obj;
            NewsAdapter newsAdapter = new NewsAdapter( MainActivity.this, listNewsBean );
            listview.setAdapter( newsAdapter );



            
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );
        mContext = MainActivity.this;
        listview = (ListView) findViewById( R.id.list_news );
        newsUtils = new NewsUtils();
        NewsDBUtils newsDatabase = new NewsDBUtils( mContext );

        // 1.��ȥ���ݿ��л�ȡ�������������չʾ��listview
        ArrayList<NewsBean> allnews_database = NewsUtils.getDBNews( mContext );

        if (allnews_database != null && allnews_database.size() > 0) {
            // ����һ��adapter���ø�listview
            NewsAdapter newsAdapter = new NewsAdapter( mContext, allnews_database );
            listview.setAdapter( newsAdapter );
        }

        new Thread( new Runnable() {

            @Override
            public void run() {
                listNewsBean = newsUtils.getNetNews( mContext, result );
                Message message = Message.obtain();
                message.obj = listNewsBean;
                mHandler.sendMessage( message );
            }
        } ).start();

        listview.setOnItemClickListener( this );

    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        NewsBean news = (NewsBean) adapterView.getItemAtPosition(i);
        String url = news.getNews_url();
        Intent intent = new Intent();
        intent.setAction( Intent.ACTION_VIEW );
        intent.setData( Uri.parse( url ) );
        startActivity( intent );
    }

}
